<template>
    <div class="red-book-form">
         <a-form layout="vertical" >
           <a-form-item label="标题"  v-bind="validateInfos.title">
             <a-input v-model:value="formRef.title" placeholder="请输入标题" />
           </a-form-item>  
           <a-form-item label="封面" v-bind="validateInfos.cover_img" >
           
             <a-upload
                     :action="$utils.imgAction"
                     :headers="{ 'org-token': $store.getters.token }"
                     v-model:file-list="imgInfoList"
                     @change="handleLogoUpload"
                     @preview="handlePreview"
                     :multiple="imgMinNum>1"
                     name="image"
                     :data="{ dir: 'work_ai' }"
                     accept="image/*"
                     list-type="picture-card"
                   >
                     <div v-if="!formRef.cover_img.length||formRef.cover_img.length<imgMaxNum">
                       <PlusOutlined />
                       <div>上传封面</div>
                     </div>
               </a-upload>
             </a-form-item>
            
          
           <a-form-item label="发布时间" required>
             <a-radio-group v-model:value="formRef.publishType">
               <a-radio :value="1">立即发布</a-radio>
               <a-radio :value="2">定时发布</a-radio>
            </a-radio-group>
           </a-form-item>
           <a-form-item  v-if="formRef.publishType==2"  v-bind="validateInfos.fix_at">
               <a-date-picker :disabledDate="disabledDate"  :disabled-time="disabledDateTime" :show-time="{ format:'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm" placeholder="请选择时间" @change="onTimeChange" />
           </a-form-item>
         </a-form>
         <a-modal :visible="previewVisible" :footer="null" @cancel="()=>previewVisible=false">
          <img alt="example" style="width: 100%" :src="previewImage" />
         </a-modal>
    </div> 
 </template>
   
   <script>
   import {
     defineComponent,
     reactive,
     toRefs,
     computed,
     watchPostEffect,
     ref,
   } from "vue";
   import { useVModel } from '@vueuse/core'
   import request from "../../../common/utils/request"
   import utils from "@/common/utils/utils"
   import { useRoute, useRouter } from "vue-router";
   import moment from 'moment'
   import { Modal, notification, message,Form } from "ant-design-vue";
   import { CloseOutlined, SyncOutlined,PlusOutlined } from "@ant-design/icons-vue";
   import _ from  'lodash'
  
   import { useDebounceFn } from '@vueuse/core'
 import { watch } from "vue";
 import { nextTick } from "vue";
   let qrCodeTimer = null;
   export default defineComponent({
     name: "twitter",
     components: { CloseOutlined, SyncOutlined,PlusOutlined },
     formData: {
       title: '',
       cover_img: [],
       publishType:1,
       fix_at:null,
     },
     props: {
       visible: {
         type: Boolean,
         default: false,
       },
       formData:{
         type: Object,
         default: ()=>null
       },
       title:{
         type: String,
         default: '',
       },
       accountId:{
         type:[Number,String],
         default:''
       },
       content:{
         type: String,
         default: '',
       },
       group_account_list:{
        type: Array,
        default: ()=>[]
      },
     },
     
     setup(props, context) {
       const state = reactive({
         previewImage:'',
         previewVisible:false,
         publishTime:'',
    
         isRequired:false,
       });
       
       const formRef = useVModel(props, 'formData', context.emit)
 
       const useForm = Form.useForm;
       
      
       let  imgInfoList = ref([])
       let validate_cover_img = async(_rule, value)=>{
         if(imgMinNum.value>0&&imgInfoList.value.length==0){
           return Promise.reject('请上传封面');
         }else{
           return Promise.resolve();
         }
      }
      let validate_time = ()=>{
      
         if(formRef.value.publishType==2&&!formRef.value.fix_at){
          
           return Promise.reject('请选择发布时间');
         }else{
           return Promise.resolve();
         }
      }
      const conentTxt = computed(()=>{
        let pureText = props.content.replace(/(<([^>]+)>)/gi, '');
        return pureText
      })
      let validate_title = () => {

         if (formRef.value.title.length == 0) {
           return Promise.reject('请填写标题');
         }
         if (conentTxt.value.length > 280) {
           console.log(conentTxt.value.length);
           return Promise.reject('Twitter文章字数不能大于280');
         }
         return Promise.resolve();
       }
       const onTimeChange = (e)=>{
        
         formRef.value.fix_at = e?moment(e).format('YYYY-MM-DD HH:mm'):null
       }
       
         const handleLogoUpload = (info)=>{
        
           let resFileList = [...info.fileList];
         if (resFileList.length) {
           resFileList.map((file, index) => {
             if (file.response) {
               if (file.response.code == 1000) {
                 file.url = file.response.data.fileUrl;
               } else {
                 message.warning(file.response.msg);
                 resFileList.splice(index, 1);
               }
             }
           });
         }
         
         imgInfoList.value = resFileList;
         formRef.value.cover_img = resFileList.map(item=>{
           return item.url
         })
       
        
         }
      
       
     
       const imgMaxNum = computed(()=>{
         return props.group_account_list.find(item=>item.key=='twitter')?.max_upload_number || 0
        
       })
       const imgMinNum = computed(()=>{
         return props.group_account_list.find(item=>item.key=='twitter')?.min_upload_number || 0
         
        
       })
    
    
  
        
       watch(() => formRef.value.publishType, (val) => {
         if (val ==2 ) {
           validate(['fix_at'])
         }
       })
       const rulesRef = reactive({
       title: [
           { required: true,  validator: validate_title,},
         ],
         cover_img:[
           {
            required:imgMinNum.value>0,
             validator: validate_cover_img,
             trigger: 'change',
           }
         ],
         fix_at:[
           {
             required:true,
             validator: validate_time,
             trigger: 'change',
           }
         ],
      })
     
      const { resetFields ,validate,validateInfos } = useForm(formRef, rulesRef)
      watch(()=>props.title,(newTitle,oldTitle)=>{
         if(! formRef.value.title || formRef.value.title == oldTitle){
           formRef.value.title = props.title
         }
         },
         {immediate:true})
         watch(() => imgMinNum.value, (val) => {
 
         if (val > 0) {
           validateInfos.cover_img.required = true
          
         }
       })
       const disabledDate= (current)=>{
         // 时间组件当前日期之前的日期不能选择
         return current && current < moment().startOf('day')
       }
       const disabledDateTime = (choosTime) => {
      let currentHour = moment().hour()
      let currentMinute = moment().minute()
    
      let disabledMinutes =  () => []
      let disabledHours = ()=>[]
      if(choosTime){
        disabledMinutes = moment(choosTime)>moment()?
       () => []:
       () => Array.from({ length: 61 }, (_, index) => index).splice(0, currentMinute + 1)

       disabledHours = moment(choosTime)>moment()?() => []:
       () => Array.from({ length: 25 }, (_, index) => index).splice(0, currentHour)
      }

      return {
        disabledHours,
        disabledMinutes,

      };
    }
       const handlePreview = async (file )=>{
           if (!file.url && !file.preview) {
           file.preview = await getBase64(file.originFileObj);
         }
         state.previewImage = file.url || file.preview;
         state.previewVisible = true;
       }
       const getBase64 = (file)=>{
         return new Promise((resolve, reject) => {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result);
         reader.onerror = error => reject(error);
   });
       }
       watch(()=>props.content,()=>{
       
       let {images}  = utils.parseRichText(props.content)
    
       if( formRef.value.cover_img.length==0){
           formRef.value.cover_img = images.slice(0,imgMaxNum.value)
         
           imgInfoList.value = images.slice(0,imgMaxNum.value).map((item,index)=>{
           return {
             uid: index,
             name: 'image.png',
             status: 'done',
             url: item,
           }
         })
         
       }
    
    },{deep:true,immediate:true})
       return {
         ...toRefs(state),
         onTimeChange,
         formRef,
         handleLogoUpload,
         imgInfoList,
         imgMaxNum,
         imgMinNum,
         rulesRef,
         validate,
         validateInfos,
         disabledDate,
         disabledDateTime,
         handlePreview,
       
       };
     },
   });
   </script>
   
   <style lang="less" scoped>
   :deep(.ss-row){
     flex-wrap: unset;
   }
   :deep(.ss-form-item-has-error .ss-upload){
     background-color: #fff;
     border-color: #ff4d4f;
   }                        
   </style>
   